from PIL import Image
import os


def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024
def get_outfile(infile, outfile):
    if outfile:
        return outfile
    dir, suffix = os.path.splitext(infile)
    outfile = '{}-out{}'.format(dir, suffix)
    return outfile

def compress_image(infile, outfile='', mb=150, step=5, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标，KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址，压缩文件大小
    """
    print('mb===',mb)
    o_size = get_size(infile)
    print('o_size',o_size)
    if o_size <= mb:
        return infile
    outfile = get_outfile(infile, outfile)
    print('outfile',outfile)
    while o_size > mb:
        im = Image.open(infile)
        if infile.lower().endswith('.png'):
            im = im.convert('RGB')
            outfile=outfile.replace('.png','.jpg')
    
        im.save(outfile,'jpeg', quality=quality)
        if quality - step < 0:
            break
        if quality<10:
            quality=quality-1
        else:
            quality -= step
        o_size = get_size(outfile)
        #print('o_size',o_size)
    return outfile, get_size(outfile)


def listdir(path, list_name):  # 传入存储的list
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if not os.path.isdir(file_path):
            list_name.append(file_path)
        # if os.path.isdir(file_path):
        #     listdir(file_path, list_name)
        # else:
        #     list_name.append(file_path)

def isImage(file):
    nameList=file.split('.')
    if len(nameList)>1:
        if nameList[len(nameList)-1].lower()=='png' or nameList[len(nameList)-1].lower()=='jpg' :
            return True
    return False
def getRealFileName(file):
    fileName=os.path.basename(file)
    return fileName
    # nameList=fileName.split('.')
    # if len(nameList)>1:
    #     fileType=nameList.pop()
    #     realName=''
    #     for bean in nameList:
    #         realName=realName+bean
    #     return [realName,fileType]
    # return [fileName,'jpg']


print('请输入压缩方式')
print('1.压缩到固定大小（单位KB）')
print('2.按比例压缩（单位百分比）')

type=input("请选择输入方式（数字）")
print(type)
if type=='1':
    fileSize=int(input("请输入希望的文件大小（单位KB）"))
if type=='2':
    fileSize=int(input("请输入希望的文件大小（单位百分比）"))
if type=='1' or type =='2':
    fileList=[]
    imageList=[]
    workDir=os.getcwd()
    outDir=workDir+'\\out\\'


    if not os.path.exists(outDir):
        os.makedirs(outDir)

    print("当前目录",workDir)
    listdir(workDir,fileList)
    for file in fileList:
        if isImage(file):
            print(file)
            imageList.append(file)
    for image in imageList:
        print('getRealFileName',getRealFileName(image))
        realName=getRealFileName(image)
        if type=='1':
            compress_image(image,outDir+realName,fileSize)
        elif type=='2':
            compress_image(image,outDir+realName,get_size(image)*fileSize/100)
else:
    print('输入错误')

